package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.common.model.Option;
import com.settlement.system.mapper.SysPlatformIdLinkMapper;
import com.settlement.system.mapper.SysPlatformMapper;
import com.settlement.system.model.entity.SysDictType;
import com.settlement.system.model.entity.SysPlatform;
import com.settlement.system.model.entity.SysPlatformIdLink;
import com.settlement.system.model.form.PlatformForm;
import com.settlement.system.model.query.PlatformPageQuery;
import com.settlement.system.service.SysDictService;
import com.settlement.system.service.SysDictTypeService;
import com.settlement.system.service.SysPlatformService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.settlement.system.common.constant.SystemConstants.DICT_TYPE_CACHE_PREFIX;
import static com.settlement.system.common.constant.SystemConstants.PLATFORM_CACHE_PREFIX;

/**
 * <p>
 * 平台设置 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-21
 */
@Service
@RequiredArgsConstructor
public class SysPlatformServiceImpl extends ServiceImpl<SysPlatformMapper, SysPlatform> implements SysPlatformService {

    private final SysDictTypeService dictTypeService;

    private final SysDictService sysDictService;
    private final RedisTemplate redisTemplate;

    private final SysPlatformIdLinkMapper platformIdLinkMapper;

    @Override
    public Page<SysPlatform> getPlatformPage(PlatformPageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();
        return this.page(
                new Page<>(pageNum, pageSize),
                new LambdaQueryWrapper<SysPlatform>()
                        .like(StrUtil.isNotBlank(keywords), SysPlatform::getPlatformName, keywords)
        );
    }

    @Override
    public SysPlatform getPlatformFormData(Long platformId) {
        return this.baseMapper.selectById(platformId);
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean savePlatform(PlatformForm platformForm) {
        SysPlatform platform = new SysPlatform();
        BeanUtil.copyProperties(platformForm, platform);
        if (platformForm.getId() == null) {
            long count = this.count(new LambdaQueryWrapper<SysPlatform>()
                    .eq(SysPlatform::getPlatformKey, platformForm.getPlatformKey())
            );
            Assert.isTrue(count == 0, "平台设置已存在");
        } else {
            long count = this.count(new LambdaQueryWrapper<SysPlatform>()
                    .eq(SysPlatform::getPlatformKey, platformForm.getPlatformKey())
                    .ne(SysPlatform::getId, platformForm.getId())
            );
            Assert.isTrue(count == 0, "平台设置已存在");
        }
        // 删除缓存
        redisTemplate.delete(PLATFORM_CACHE_PREFIX + platform.getPlatformKey());
        return saveOrUpdate(platform);
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean deletePlatforms(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的平台数据为空");
        // 逻辑删除
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .map(Long::parseLong).collect(Collectors.toList());
        List<SysPlatform> list = this.list(new LambdaQueryWrapper<SysPlatform>()
                .eq(SysPlatform::getId, ids));
        for (SysPlatform sysPlatform : list) {
            // 删除缓存
            redisTemplate.delete(PLATFORM_CACHE_PREFIX + sysPlatform.getPlatformKey());
        }
        return this.removeByIds(ids);
    }

    @Override
    @SuppressWarnings("unchecked")
    public SysPlatform getByPlatformKey(String platformKey) {
        Object value = redisTemplate.opsForValue().get(PLATFORM_CACHE_PREFIX + platformKey);
        if (value != null) {
            return (SysPlatform) value;
        }
        // 查一次数据库
        SysPlatform sysPlatform = this.getOne(new LambdaQueryWrapper<SysPlatform>().eq(SysPlatform::getPlatformKey,
                platformKey));
        // 放入缓存
        redisTemplate.opsForValue().set(PLATFORM_CACHE_PREFIX + platformKey, sysPlatform, 1, TimeUnit.HOURS);
        return sysPlatform;
    }

    @Override
    public SysDictType getSysDictTypeByDictName(String dictName) {
        Object value = redisTemplate.opsForValue().get(DICT_TYPE_CACHE_PREFIX + dictName);
        if (value != null) {
            return (SysDictType) value;
        }
        SysDictType sysDictType = dictTypeService.getOne(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getName, dictName));
        redisTemplate.opsForValue().set(DICT_TYPE_CACHE_PREFIX + dictName, sysDictType, 1, TimeUnit.HOURS);
        return sysDictType;
    }

    @Override
    public SysDictType getSysDictTypeByDictCode(String dictCode) {
        Object value = redisTemplate.opsForValue().get(DICT_TYPE_CACHE_PREFIX + dictCode);
        if (value != null) {
            return (SysDictType) value;
        }
        SysDictType sysDictType = dictTypeService.getOne(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getCode, dictCode));
        redisTemplate.opsForValue().set(DICT_TYPE_CACHE_PREFIX + dictCode, sysDictType, 1, TimeUnit.HOURS);
        return sysDictType;
    }

    @Override
    public List<Option> getDictListFromDictType(String dictType) {
        return sysDictService.listDictOptions(dictType);
    }

    @Override
    public List<SysPlatformIdLink> getPlatformIdLinkListBySubNo(String platformKey, String subNo) {
        return platformIdLinkMapper.selectList(new LambdaQueryWrapper<SysPlatformIdLink>().eq(SysPlatformIdLink::getPlatfrom, platformKey).eq(SysPlatformIdLink::getSubNo, subNo));
    }

    @Override
    public List<SysPlatformIdLink> getPlatformIdLinkListByMainNo(String platformKey, String mainNo) {
        return platformIdLinkMapper.selectList(new LambdaQueryWrapper<SysPlatformIdLink>().eq(SysPlatformIdLink::getPlatfrom, platformKey).eq(SysPlatformIdLink::getMainNo, mainNo));
    }

    @Override
    public List<SysPlatform> getPlatformList() {
        List<SysPlatform> platformList = this.list();
        List<Option> options = sysDictService.listDictOptions(SystemConstants.PLATFORM_KEY);
        for (SysPlatform sysPlatform : platformList) {
            options.stream().filter(item -> Objects.equals(item.getValue(), sysPlatform.getPlatformKey())).findFirst().ifPresent(item -> sysPlatform.setPlatformName(item.getLabel()));
        }
        return platformList;
    }
}
